package dao

import (
	"fmt"
	"github.com/gogap/logs"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/profit"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

// SetUserStewardStatus  获取代理商用户列表
func (d *UserDao) SetUserStewardStatus(param *request.SetUserStewardStatusReq) *dingo.ErrorWrap {
	db := global.Orm.Table("users").Where("id=?", param.UserId)
	db.Update("is_steward", param.IsSteward)

	return dingo.ErrorIf(db.Error)

}

// GetAgentUserList 获取代理商用户列表
func (d *UserDao) GetAgentUserList(param *request.UserList) *dingo.ErrorWrap {

	var (
		lst    []*users.UserInfoWithAgent
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().
		Table("users u").
		Select("u.*", "r.name as role_name").
		Joins("left join roles r on r.id = u.role_id").
		Where("u.is_delete = 0").
		Where("u.is_admin = ?", param.IsAdmin).
		Where("u.is_place = ?", param.IsPlace)
	if param.SearchText == "" && param.Phone == "" && param.UserNo == "" {
		db.Where("u.parent_id = ?", param.ParentId)
	}

	//if param.UserLoginIsAdmin != helper.TypeNumIsAdminOperator {
	//	db.Where("u.parent_id = ?", param.ParentId)
	//}

	if param.SearchText != "" {
		db.Where("u.user_name like ?", fmt.Sprint("%", param.SearchText, "%"))
		//db.Where("u.user_name = ?", param.SearchText)
	}
	if param.Name != "" {
		db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%"))
		//db.Where("u.name = ?", param.Name)
	}
	if param.Phone != "" {
		db.Where("u.phone = ?", param.Phone)
	}
	if param.Status > 0 {
		db.Where("u.status = ?", param.Status)
	}

	if param.UserNo != "" {
		db.Where("u.user_no = ?", param.UserNo)
	}

	if param.IsTianHai > 0 {
		db.Where("u.is_tianhai = ?", param.IsTianHai)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("u.last_login_time >= ? and u.last_login_time <= ?", beginTime[0], beginTime[1])
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("u.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("u.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}

// 获取代理商下级列表
func (d *UserDao) GetAgentUserListByParentId(parentId int, isAdmin uint8) *dingo.ErrorWrap {

	lst := make([]*users.UserInfoWithAgent, 0)
	sql := `select u.*,r.name as role_name from users u left join roles r on r.id = u.role_id where
u.parent_id = ? and u.is_admin = ? and u.is_place = 0 and u.is_delete = 0`
	db := global.Orm.Debug().Raw(sql, parentId, isAdmin).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) GetTeamAnalysisList(param *request.GetAgentUserListByParentIdLimit, isAdmin uint8) *dingo.ErrorWrap {
	var (
		lst    []*request.GetAgentUserListByParentIdReq
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("users")

	if len(param.IsAdmins) > 0 {
		db.Where("is_admin IN ?", param.IsAdmins)
	}

	if param.UserName != "" {
		userName := "%" + param.UserName + "%"
		db.Where("user_name LIKE ?", userName)
	}

	if param.Name != "" {
		userName := "%" + param.Name + "%"
		db.Where("`name` LIKE ?", userName)
	}

	if param.Phone != "" {
		db.Where("phone = ?", param.Phone)
	}

	if isAdmin == 9 {
		db.Where("parent_id = ?", param.UserId)
	} else {
		userIdArr := NewUserDao().QueryChildUserIds(param.UserId).Unwrap().([]int)
		logs.Info("当前用户下的所有子用户", param.UserId, userIdArr)
		db.Where("id IN (?)", userIdArr)
	}
	db.Order("create_at DESC")
	db.Limit(limit).Offset(offset).Find(&lst).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// 获取代理商下级列表
func (d *UserDao) GetIsAdminUserListByParentId(parentId int, isAdmin uint8) *dingo.ErrorWrap {

	lst := make([]*users.UserInfoWithAgent, 0)
	sql := `select u.*,r.name as role_name from users u left join roles r on r.id = u.role_id where
u.parent_id = ? and u.is_admin = ?  and u.is_delete = 0`
	db := global.Orm.Debug().Raw(sql, parentId, isAdmin).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// InsertAgentUser 新代理商用户
func (d *UserDao) InsertAgentUser(param *request.AdminUserInsertReq) *dingo.ErrorWrap {
	db := global.Orm.Debug()
	var userId int
	err := db.Transaction(func(tx *gorm.DB) error {
		m := users.New().Mutate(
			users.WithCreateAt(dingo.Time(time.Now().Unix())),
			users.WithName(param.Name),
			users.WithUserName(param.UserName),
			users.WithNickName(param.UserName),
			users.WithPhone(param.Phone),
			users.WithPhoneCode("+86"),
			users.WithStatus(param.Status),
			users.WithPassword(utils.EncryptPassword(param.Password)),
			users.WithRoleId(param.RoleId),
			users.WithParentId(param.ParentId),
			users.WithIsAdmin(param.IsAdmin),
			users.WithIsDraw(param.IsDraw),
			users.WithIsCash(param.IsCash),
			users.WithProfitType(param.ProfitType),
			users.WithProfitIsVisible(param.ProfitIsVisible),
			users.WithOrderIsVisible(param.OrderIsVisible),
			users.WithIncomeIsVisible(param.IncomeIsVisible),
			users.WithProfitProportion(param.ProfitProportion),
			users.WithSmProfitProportion(param.SmProfitProportion),
			users.WithUserNo(helper.PrefixAgentUserNo+time.Now().Format("20060102150405")),
			users.WithUserLevel(param.UserLevel),
			users.WithIsDivinds(param.IsDivinds),
			users.WithIsDividendsSm(param.IsDividendsSm),
			users.WithTaxRate(param.TaxRate),
			users.WithTaxRateRoom(param.TaxRateRoom),
			users.WithTaxRateGoods(param.TaxRateGoods),
			users.WithTaxRateAutomate(param.TaxRateAutomate),
			users.WithRegionIds(param.RegionIds),
			users.WithProvince(param.Province),
			users.WithCity(param.City),
			users.WithCounty(param.County),
			users.WithIsSteward(param.IsSteward),
			users.WithModule(param.Module),
			users.WithPlatform(param.Platform),
		)
		if err := tx.Table("users").Create(&m).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		userId = m.ID
		// 分成表 密码线 PCL - 暂时使用的是users表中的分成，后期有改动时再用这个
		p := profit.New().Mutate(
			profit.WithCreateAt(dingo.Time(time.Now().Unix())),
			profit.WithUserID(m.ID),
			profit.WithSharedMode("pcl"),
			profit.WithDeviceTypeId(10),
			profit.WithProfitType(1),
			profit.WithProfitIsVisible(param.ProfitIsVisible),
			profit.WithProfitProportion(param.ProfitProportion),
		)

		if err := tx.Debug().Table("profits").Create(&p).Error; err != nil {
			return err
		}

		// 分成表 售货机 sm - 暂时使用的是users表中的分成，后期有改动时再用这个
		p2 := profit.New().Mutate(
			profit.WithCreateAt(dingo.Time(time.Now().Unix())),
			profit.WithUserID(m.ID),
			profit.WithSharedMode("cdb"),
			profit.WithDeviceTypeId(11),
			profit.WithProfitType(1),
			profit.WithProfitIsVisible(param.ProfitIsVisible),
			profit.WithProfitProportion(param.SmProfitProportion),
		)

		if err := tx.Debug().Table("profits").Create(&p2).Error; err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})
	return dingo.ErrorIf(err, userId)
}

// UpdateAgentUser 更新代理商用户信息
func (d *UserDao) UpdateAgentUser(param *request.AdminUserInsertReq) *dingo.ErrorWrap {
	err := global.Orm.Transaction(func(tx *gorm.DB) error {
		dbData := map[string]interface{}{
			"update_at":            dingo.Time(time.Now().Unix()),
			"name":                 param.Name,
			"user_name":            param.UserName,
			"nick_name":            param.UserName,
			"phone":                param.Phone,
			"status":               param.Status,
			"role_id":              param.RoleId,
			"parent_id":            param.ParentId,
			"user_level":           param.UserLevel,
			"profit_is_visible":    param.ProfitIsVisible,
			"order_is_visible":     param.OrderIsVisible,
			"income_is_visible":    param.IncomeIsVisible,
			"profit_proportion":    param.ProfitProportion,
			"sm_profit_proportion": param.SmProfitProportion,
			"is_admin":             param.IsAdmin,
			"is_draw":              param.IsDraw,
			"is_cash":              param.IsCash,
			"is_divinds":           param.IsDivinds,
			"is_dividends_sm":      param.IsDividendsSm,
			"tax_rate":             param.TaxRate,
			"tax_rate_room":        param.TaxRateRoom,
			"tax_rate_goods":       param.TaxRateGoods,
			"tax_rate_automate":    param.TaxRateAutomate,
			"province":             param.Province,
			"city":                 param.City,
			"county":               param.County,
			"region_ids":           param.RegionIds,
			"module":               param.Module,
			"is_steward":           param.IsSteward,
			"platform":             param.Platform,
		}
		//m := users.New().Mutate(
		//	users.WithUpdateAt(dingo.Time(time.Now().Unix())),
		//	users.WithName(param.Name),
		//	users.WithUserName(param.UserName),
		//	users.WithNickName(param.UserName),
		//	users.WithPhone(param.Phone),
		//	users.WithStatus(param.Status),
		//	users.WithRoleId(param.RoleId),
		//	users.WithParentId(param.ParentId),
		//	users.WithUserLevel(param.UserLevel),
		//	//users.WithProfitType(param.ProfitType),
		//	users.WithProfitIsVisible(param.ProfitIsVisible),
		//	users.WithProfitProportion(param.ProfitProportion),
		//	users.WithSmProfitProportion(param.SmProfitProportion),
		//
		//	users.WithIsAdmin(param.IsAdmin),
		//	users.WithIsDraw(param.IsDraw),
		//	users.WithIsCash(param.IsCash),
		//	users.WithIsDivinds(param.IsDivinds),
		//	users.WithTaxRate(param.TaxRate),
		//)
		tx.Debug().Table("users").Where("id = ? AND id<>?", param.Id, param.ParentId).Updates(dbData)
		if err := tx.Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}

		// 分成表 密码线 PCL - 暂时使用的是users表中的分成，后期有改动时再用这个
		p := profit.New().Mutate(
			profit.WithUpdateAt(dingo.Time(time.Now().Unix())),
			profit.WithUserID(param.Id),
			profit.WithProfitProportion(param.ProfitProportion),
		)
		tx.Debug().Table("profits").
			Where("user_id = ?", param.Id).
			Where("shared_mode = ?", "pcl").Model(&p).Updates(p)
		if err := tx.Error; err != nil {
			return err
		}

		// 分成表 售货机 sm - 暂时使用的是users表中的分成，后期有改动时再用这个
		p2 := profit.New().Mutate(
			profit.WithUpdateAt(dingo.Time(time.Now().Unix())),
			profit.WithUserID(param.Id),
			profit.WithProfitProportion(param.SmProfitProportion),
		)
		tx.Debug().Table("profits").
			Where("user_id = ?", param.Id).
			Where("shared_mode = ?", "cdb").Model(&p2).Updates(p2)
		if err := tx.Error; err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})

	return dingo.ErrorIf(err, true)
}

func (d *UserDao) GetAgentUserLists() *dingo.ErrorWrap {

	var lst []users.AgentInfo
	isAdmins := []int{helper.TypeNumIsAdminOperator, helper.TypeNumIsAdminMerchant, helper.TypeNumIsAdminBranch,
		helper.TypeNumIsAdminKaProject, helper.TypeNumIsAdminRegion, helper.TypeNumIsAdminResource}
	sql := "select * from users where is_admin in (?) and is_delete = 0"
	db := global.Orm.Debug().Raw(sql, isAdmins).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) GetSingleAgentUser(userId int) *dingo.ErrorWrap {

	agentInfo := users.AgentInfo{}
	sql := "select * from users where is_admin = 3 and is_place = 0  and is_delete = 0 and id = ? "
	db := global.Orm.Debug().Raw(sql, userId).Find(&agentInfo)

	return dingo.ErrorIf(db.Error, agentInfo)
}

func (d *UserDao) GetOperatingUser(userId int) *dingo.ErrorWrap {

	agentInfo := users.AgentInfo{}
	sql := "select * from users where  is_delete = 0 and id = ? "
	db := global.Orm.Debug().Raw(sql, userId).Find(&agentInfo)

	return dingo.ErrorIf(db.Error, agentInfo)
}

func (d *UserDao) GetBranchUserLists() *dingo.ErrorWrap {

	var lst []users.AgentInfo
	sql := "select * from users where is_admin = 5  and is_delete = 0"
	db := global.Orm.Debug().Raw(sql).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) GetSupAgentUserListByParentId(parentId int, isPlace int) *dingo.ErrorWrap {

	lst := make([]*users.UserInfoWithAgent, 0)
	db := global.Orm.
		Table("users").
		Where("is_delete = 0 ")

	if isPlace == 2 {
		db.Where("is_place = ? or id = ?", isPlace, parentId)
	} else {
		db.Where("id = ?", parentId)
	}

	db.Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 获取上级代理商
func (d *UserDao) GetSupAgentUserList() *dingo.ErrorWrap {
	var lst []users.AgentInfo
	db := global.Orm.Table("users").Where("is_delete = 0 ")
	db.Where("is_admin = 2 or is_admin = 3").Where("is_place = 0")

	db.Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) GetAllUser(userName string, userId int) *dingo.ErrorWrap {
	var lst []*users.AgentInfo

	db := global.Orm.Debug().
		Table("users").
		Select("id", "name", "user_name")
	if userName != "" {
		db.Where("user_name like ? or name like ?", fmt.Sprint("%", userName, "%"), fmt.Sprint("%", userName, "%"))
	}
	//只能查看当前登录账号的下级
	//userIds := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//db.Where("id in(?)", userIds)
	//db.Where("is_admin != 1")

	db.Order("is_admin ASC ,is_place ASC")
	db.Limit(20).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) GetAdminUserOrPlaceUser(userName string, userId int, IsAdmin uint8) *dingo.ErrorWrap {
	var lst []*users.AgentInfo

	db := global.Orm.Debug().
		Table("users").
		Select("id", "name", "user_name")

	userIdArr := []int{userId}
	if IsAdmin != helper.TypeNumIsAdminOperator {
		userIdArr = append(userIdArr, NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)...)
		db.Where("id in (?)", userIdArr)
	}

	if userName != "" {
		db.Where("user_name like ? or name like ?", fmt.Sprint("%", userName, "%"), fmt.Sprint("%", userName, "%"))
	}

	db.Where("is_admin != 1")
	//db.Where("is_place != 3")
	//db.Order("is_admin ASC ,is_place ASC, create_at DESC")
	db.Order("id DESC")
	db.Limit(20).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)

	//isAdmins := []int{helper.TypeNumIsAdminOperator, helper.TypeNumIsAdminBranch, helper.TypeNumIsAdminKaProject, helper.TypeNumIsAdminRegion, helper.TypeNumIsAdminResource, helper.TypeNumIsAdminAgent}
	//m := make([]*users.AgentInfo, 0)
	//db := global.Orm.Debug().
	//	Table("users").
	//	Select("id", "name", "user_name").
	//	Where("is_delete = 0 and is_admin in (?)", isAdmins)
	//
	//if userName != "" {
	//	nameSql := fmt.Sprint("%", userName, "%")
	//	db.Where("(name like ? or user_name like ?)", nameSql, nameSql)
	//}
	//
	//if userId != 2 { // userId为 2 时  取所有，这样就不用递归查询运营商下的所有用户了，也不需要使用 in 条件了
	//	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int) // 查询用户ID下所有下级用户ID
	//	db.Where("id in (?)", userIdArr)
	//}
	//
	//db.Order("is_admin,id asc").Limit(20).Find(&m)
	//
	//return dingo.ErrorIf(db.Error, m)

}

func (d *UserDao) GetRelPlaceUserList(userName string, userId int, IsAdmin uint8) *dingo.ErrorWrap {
	var lst []*users.AgentInfo
	db := global.Orm.Debug().
		Table("users").
		Select("id", "name", "user_name")
	userIdArr := []int{userId}
	if IsAdmin != helper.TypeNumIsAdminOperator {
		userIdArr = append(userIdArr, NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)...)
		db.Where("id in (?)", userIdArr)
	}
	if userName != "" {
		db.Where("user_name like ? or name like ?", fmt.Sprint("%", userName, "%"), fmt.Sprint("%", userName, "%"))
	}
	db.Where("is_admin = 3")
	db.Order("id DESC")
	db.Limit(30).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) InsertUserImport(m []request.UserImportReq) *dingo.ErrorWrap {

	db := global.Orm.Table("users").Create(&m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *UserDao) GetSeparateAgentUser(id int) *dingo.ErrorWrap {

	var lst users.AgentInfo
	sql := "select * from users where id = ? and is_delete = 0"
	db := global.Orm.Debug().Raw(sql, id).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// GetAgentUserList 获取代理商用户列表
func (d *UserDao) WebAppGetAgentUserList(param *request.UserList) *dingo.ErrorWrap {

	var (
		lst    []*users.UserInfoWithAgent
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().
		Table("users u").
		Select("u.*", "r.name as role_name").
		Joins("left join roles r on r.id = u.role_id").
		Where("u.is_delete = 0").
		Where("u.is_admin = ?", param.IsAdmin).
		Where("u.is_place = ?", param.IsPlace)
	if param.SearchText == "" && param.Phone == "" && param.UserNo == "" {
		db.Where("u.parent_id = ?", param.ParentId)
	}

	//if param.UserLoginIsAdmin != helper.TypeNumIsAdminOperator {
	//	db.Where("u.parent_id = ?", param.ParentId)
	//}

	if param.UserId > 0 {
		db.Where("u.id = ?", param.UserId)
	}

	if param.SearchText != "" {
		db.Where("u.user_name like ? or u.name like ?", fmt.Sprint("%", param.SearchText, "%"), fmt.Sprint("%", param.SearchText, "%"))
		//db.Where("u.user_name = ?", param.SearchText)
	}
	if param.Name != "" {
		db.Where("u.name = ?", param.Name)
	}
	if param.Phone != "" {
		db.Where("u.phone = ?", param.Phone)
	}
	if param.Status > 0 {
		db.Where("u.status = ?", param.Status)
	}

	if param.UserNo != "" {
		db.Where("u.user_no = ?", param.UserNo)
	}

	if param.IsTianHai > 0 {
		db.Where("u.is_tianhai = ?", param.IsTianHai)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("u.last_login_time >= ? and u.last_login_time <= ?", beginTime[0], beginTime[1])
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("u.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("u.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}

func (d *UserDao) WebAppGetAgentChild(userId int) *dingo.ErrorWrap {
	var lst []users.GetAgentChild
	sql := "SELECT id,parent_id FROM users WHERE parent_id in(SELECT id FROM users WHERE parent_id = ? ) "
	db := global.Orm.Debug().Raw(sql, userId).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

func (d *UserDao) WebAppGetPlaceChild(userId int, isAdmin uint8) *dingo.ErrorWrap {
	var lst []users.GetPlaceChild

	isAdminSql := ` and is_admin = ` + strconv.Itoa(int(isAdmin))
	if isAdmin != helper.TypeNumIsAdminOperator {
		isAdminSql += ``
	}

	sql := `SELECT user_id,count(id) as num FROM places WHERE user_id in(SELECT id FROM users WHERE parent_id = ? ` + isAdminSql + ` ) GROUP BY user_id`
	db := global.Orm.Debug().Raw(sql, userId).Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// GetUserListByIsAdmin 获取用户列表
func (d *UserDao) GetUserListByIsAdmin(param *request.UserList) *dingo.ErrorWrap {

	var (
		lst    []*users.UserInfoWithAgent
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("users u").
		Where("u.is_delete = 0")

	// 查询需要商户一起查询出来
	if param.UserId > 0 {
		db.Where("u.id = ?", param.UserId)
	} else if param.IsAdmin > 0 {
		db.Where("u.is_admin = ?", param.IsAdmin)
	}

	if param.ParentId > 0 && param.ParentId != 2 {
		db.Where("u.parent_id = ?", param.ParentId)
	}
	if param.UserName != "" {
		db.Where("u.user_name like ?", fmt.Sprint("%", param.UserName, "%"))
	} // 查询条件：名称
	if param.Name != "" {
		db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%"))
	} // 查询条件：姓名
	if param.Phone != "" {
		db.Where("u.phone = ?", param.Phone)
	} // 查询条件：手机号码
	if param.Status > 0 {
		db.Where("u.status = ?", param.Status)
	} // 查询条件：状态
	//if param.UserNo != "" {
	//	db.Where("u.user_no = ?", param.UserNo)
	//} // 查询条件：用户编号

	if param.IsSteward > 0 {
		db.Where("u.is_steward = ?", param.IsSteward)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("u.last_login_time >= ? and u.last_login_time <= ?", beginTime[0], beginTime[1])
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("u.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("u.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		//db.Order("u.is_admin desc")
		db.Order("u.id desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}

func (d *UserDao) GetExtSignUsersList(param *request.UserList) *dingo.ErrorWrap {
	var (
		lst    []*users.ExtSignUsers
		count  int64
		limit  = param.PageSize
		offset = param.PageSize * (param.PageNo - 1)
	)
	fieldStr := "fdd.*,u.name as user_name,u.phone,u.profit_proportion"
	db := global.Orm.Debug().Table("fdd_ext_sign_user fdd").
		Select(fieldStr).Joins("left join users u on u.id = fdd.user_id").
		Where("fdd.is_signed = 2"). //是否签署
		Where("u.is_delete = 0")
	if param.Name != "" {
		db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%"))
	}
	if param.Phone != "" {
		db.Where("u.phone = ?", param.Phone)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("u.create_at >= ? and u.create_at <= ?", beginTime[0], beginTime[1])
	}
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
	db.Order("fdd.create_at desc")
	return dingo.ErrorIf(db.Error, lst, count)
}
